﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    class ReferencePattern : Pattern
    {
        private Func<Pattern> pattern;
        private PatternMatch _cached;

        public ReferencePattern(Func<Pattern> pattern)
            : base(PatternKind.Reference)
        {
            this.pattern = pattern;
        }

        public override PatternMatch Compile()
        {
            return Target;
        }

        private async Task<IMatch> Target(IScope scope)
        {
            lock(this)
            {
                if (_cached == null)
                {
                    lock(this)
                    {
                        _cached = pattern().ToPatternMatch();
                    }
                }
            }

            return await _cached(scope);
        }
    }
}
